// pages/search/wifi/wifi.js
Page({
  /**
   * 组件的初始数据
   */
  data: {
    inputValue: "", //输入的IP地址
    wifiDevices: [], //搜索到的wifi设备列表
    isWifiSearching: false, //wifi是否正在搜索
    isWiFiStarted: false, //wifi模块是否开启
    searchMethodIndex: 0, //选中的扫描方式
    showActionsheet: false, //显示ationsheet
    serviceType: '_phibox._tcp.', //mDNS服务类型
    errorMsg: '', //错误提示
    searchMethods: [{ //wifi扫描方式
        text: 'mDNS',
        value: 1,
        type: 'warn'
      },
      {
        text: 'HTTP Ping',
        value: 2
      },
    ],
  },
  onReady: function () {
    const that = this;
    wx.onNetworkStatusChange((result) => {
      that.setData({
        isWiFiStarted: result.networkType === 'wifi'
      })
    });
    wx.onLocalServiceDiscoveryStop((res) => {
      that.setData({
        isWifiSearching: false
      });
    });
    wx.onLocalServiceFound((result) => {
      var devices = this.data.wifiDevices;
      devices.push(result);
      that.setData({
        wifiDevices: devices
      });
    });
  },
  onShow: function () {
    const that = this;
    this.setData({
        inputValue: getApp().globalData.host
      }),
      wx.getNetworkType({
        success: (result) => {
          that.setData({
            isWiFiStarted: result.networkType === 'wifi'
          })
        },
      });
  },
  onUnload: function () {
    if (this.data.isWifiSearching) {
      wx.stopLocalServiceDiscovery({
        success: (res) => {},
      })
    }
  },
  openActionSheet() {
    this.setData({
      showActionsheet: true
    })
  },
  modActionSheet(i) { //第i个是选中项
    var tmp = [];
    Object.assign(tmp, this.data.searchMethods);
    for (let index = 0; index < tmp.length; index++) {
      if (i != index) {
        tmp[index].type = 'default'
      } else {
        tmp[index].type = 'warn'
      }
    }
    this.setData({
      searchMethods: tmp
    });
  },
  onActionTap(e) {
    this.setData({
      showActionsheet: false,
      searchMethodIndex: e.detail.index,
    });
    this.modActionSheet(e.detail.index);
  },
  serachByHttp() {
    this.setData({
      percent: 0,
      isWifiSearching: true,
      wifiDevices: []
    })
    let that = this;
    var wifiDevice = [];
    var ips = this.data.inputValue.split(".").slice(0, 4);
    var completed = 0;
    console.log(ips)
    if (ips.length < 4) {
      that.setData({
        isWifiSearching: false
      });
      wx.showToast({
        title: '输入格式不正确',
        icon: 'none'
      });
      return;
    }
    var start = 1;
    var end = 255;
    var count = end - start;
    for (let i = start; i < end; i++) {
      ips[3] = i;
      let ip = ips.join(".");
      wx.request({
        url: "http://" + ip + ":8080/v1/status",
        method: 'GET',
        timeout: 300,
        complete: (result) => {
          //console.log(i)
          //console.log(result)
          completed++;
          if (completed == count) {
            that.setData({
              percent: 100,
              isWifiSearching: false
            })
          } else {
            that.setData({
              percent: parseInt(completed / count * 100)
            })
          }
          // console.log(result.data+ip)
          if (result.statusCode == 200) {
            result.data.ip = ip;
            result.data.serviceName = result.data.name;
            wifiDevice.push(result.data);
            that.setData({
              wifiDevices: wifiDevice
            });
          }
        }
      });
    }
  },
  serachBymDns() {
    console.log("开始搜索mDNS")
    const that = this;
    wx.startLocalServiceDiscovery({
      serviceType: that.data.serviceType,
      success: (res) => {
        that.setData({
          isWifiSearching: true,
          wifiDevices: []
        });
      },
      fail: (res) => {
        console.log(res)
        that.setData({
          errorMsg: res.errMsg.substring(res.errMsg.lastIndexOf(':') + 1)
        })
      }
    });
  },
  stopSerachBymDns() {
    this.setData({
      isWifiSearching: false
    });
    wx.stopLocalServiceDiscovery({
      success: (res) => {
        console.log("停止搜索mDNS")
      },
    })
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  onInputServiceType(e) {
    this.setData({
      serviceType: e.detail.value
    })
  },
  onWifiClick(e) {
    console.log(e)
    var data = Object.assign({}, getApp().globalData);
    data.host = this.data.wifiDevices[e.currentTarget.id].ip;
    console.log(data);
    this.saveSettings(data, function () {
      wx.showToast({
        title: 'IP地址已保存',
      });
      getApp().readSettingsSync();
    });
  },
  saveSettings(data, callback) {
    console.log("保存设置")
    const that = this;
    console.log(data)
    wx.setStorage({
      key: 'settings',
      data: data,
      success: callback,
      fail: () => {
        that.setData({
          errorMsg: "保存失败"
        })
      }
    });
  },
})